package com.happy3w.ssp.schoolmatehome.component.image.type.text;

import com.happy3w.ssp.schoolmatehome.component.image.DrawAction;
import com.happy3w.ssp.schoolmatehome.component.image.LinePrintContext;
import com.happy3w.ssp.schoolmatehome.component.image.LocationDrawAction;
import com.happy3w.ssp.schoolmatehome.component.image.TypePrinter;
import org.springframework.stereotype.Component;

import java.awt.FontMetrics;
import java.awt.Point;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class TextPrinter implements TypePrinter<String> {

    private static final Set<Character> SpecialChars = Set.of(' ', ',', '.', '\'', '\"', '-', '+', '=', ')', '}', ']', '>', '<', ';', ':');
    @Override
    public List<DrawAction> buildActions(String item, LinePrintContext context) {
        FontMetrics fontMetrics = context.getFontMetrics();
        char[] chars = item.toCharArray();
        StringBuilder lineBuf = new StringBuilder();

        List<DrawAction> actions = new ArrayList<>();
        int startX = context.getLocation().x;
        int curX = startX;
        for (char c : chars) {
            int charWidth = fontMetrics.charWidth(c);
            if (curX + charWidth > context.getWidth()) {
                char preCh = 0;
                if (SpecialChars.contains(c)) {
                    preCh = lineBuf.charAt(lineBuf.length() - 1);
                    lineBuf.setLength(lineBuf.length() - 1);
                }

                actions.add(new TextAction(lineBuf.toString(), new Point(startX, context.getLocation().y)));
                lineBuf.setLength(0);
                context.nextLine();
                startX = context.getLocation().x;
                curX = startX;

                if (preCh != 0) {
                    lineBuf.append(preCh);
                    curX += fontMetrics.charWidth(preCh);
                }
            }

            lineBuf.append(c);
            curX += charWidth;
        }

        if (!lineBuf.isEmpty()) {
            actions.add(new TextAction(lineBuf.toString(), new Point(startX, context.getLocation().y)));
        }

        context.getLocation().x = curX;

        return actions;
    }

    @Override
    public boolean isSupport(Object item) {
        return item instanceof String;
    }
}
